package v1

import (
	"context"
	"net/http"
	"strings"

	apb "quipus/proto/gen/assist"
	cpb "quipus/proto/gen/common"

	"github.com/golang-jwt/jwt/v5"

	"quipus/internal/database/dao"
	model "quipus/internal/database/model"
	"quipus/internal/utils"

	"github.com/pkg/errors"
	"google.golang.org/grpc"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/metadata"
	"google.golang.org/grpc/status"
)

// ContextKey is the key type of context value.
type ContextKey int

const (
	// The key name used to store username in the context
	// user id is extracted from the jwt token subject field.
	usernameContextKey ContextKey = iota
	accessTokenContextKey
	userIdContextKey
	tenantIdContextKey
)

var authenticationAllowlistMethods = map[string]bool{
	"/qps.api.v1.SystemService/GetSystemProfile":                true,
	"/qps.api.v1.SystemSettingService/GetSystemSetting":         true,
	"/qps.api.v1.SystemSettingService/ListSystemSettings":       true,
	"/qps.api.v1.IdentityProviderService/GetIdentityProvider":   true,
	"/qps.api.v1.IdentityProviderService/ListIdentityProviders": true,
	"/qps.api.v1.AuthService/GetAuthStatus":                     true,
	"/qps.api.v1.AuthService/SignIn":                            true,
	"/qps.api.v1.AuthService/SignInWithSSO":                     true,
	// "/qps.api.v1.HelloService/SayHello":                         true,
	"/qps.api.v1.TopicService/ListTopics":           true,
	"/qps.api.v1.TopicService/ListTopicTypes":       true,
	"/qps.api.v1.AuthService/SignOut":               true,
	"/qps.api.v1.AuthService/SignUp":                true,
	"/qps.api.v1.UserService/GetUser":               true,
	"/qps.api.v1.UserService/GetUserAvatarBinary":   true,
	"/qps.api.v1.UserService/SearchUsers":           true,
	"/qps.api.v1.KnotService/GetKnot":               true,
	"/qps.api.v1.KnotService/GetKnotByUid":          true,
	"/qps.api.v1.KnotService/ListKnots":             true,
	"/qps.api.v1.KnotService/ListKnotTags":          true,
	"/qps.api.v1.MarkdownService/GetLinkMetadata":   true,
	"/qps.api.v1.ResourceService/GetResourceBinary": true,
	"/qps.api.v1.ResourceService/GetResourceByUid":  true,
}

// isUnauthorizeAllowedMethod returns whether the method is exempted from authentication.
func isUnauthorizeAllowedMethod(fullMethodName string) bool {
	return authenticationAllowlistMethods[fullMethodName]
}

var allowedMethodsOnlyForAdmin = map[string]bool{
	"/qps.api.v1.UserService/CreateUser":                true,
	"/qps.api.v1.SystemSettingService/SetSystemSetting": true,
}

// isOnlyForAdminAllowedMethod returns true if the method is allowed to be called only by admin.
func isOnlyForAdminAllowedMethod(methodName string) bool {
	return allowedMethodsOnlyForAdmin[methodName]
}

// GRPCAuthInterceptor is the auth interceptor for gRPC server.
type GRPCAuthInterceptor struct {
	db      *dao.Driver
	handler dao.DBOperator
	secret  string
}

// NewGRPCAuthInterceptor returns a new API auth interceptor.
func NewGRPCAuthInterceptor(db *dao.Driver, secret string, handler dao.DBOperator) *GRPCAuthInterceptor {
	return &GRPCAuthInterceptor{
		db:      db,
		secret:  secret,
		handler: handler,
	}
}

// AuthenticationInterceptor is the unary interceptor for gRPC API.
func (in *GRPCAuthInterceptor) AuthenticationInterceptor(ctx context.Context, request any, serverInfo *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (any, error) {
	md, ok := metadata.FromIncomingContext(ctx)
	if !ok {
		return nil, status.Errorf(codes.Unauthenticated, "failed to parse metadata from incoming context")
	}
	accessToken, err := getTokenFromMetadata(md)
	if err != nil {
		return nil, status.Errorf(codes.Unauthenticated, err.Error())
	}

	user, err := in.authenticate(ctx, accessToken)

	if err != nil {
		if isUnauthorizeAllowedMethod(serverInfo.FullMethod) {
			return handler(ctx, request)
		}
		return nil, err
	}
	// user, err := in.handler.GetUser(ctx, &apb.FindUser{
	// 	Username: username,
	// })

	if user.RowStatus == cpb.RowStatus_ARCHIVED.String() {
		return nil, errors.Errorf("user %q is archived", user.Username)
	}

	if isOnlyForAdminAllowedMethod(serverInfo.FullMethod) && user.Role != cpb.Role_HOST.String() && user.Role != cpb.Role_ADMIN.String() && user.Role != cpb.Role_TENANT_ADMIN.String() {
		return nil, errors.Errorf("user %q is not admin", user.Username)
	}

	ctx = context.WithValue(ctx, usernameContextKey, user.Username)
	ctx = context.WithValue(ctx, accessTokenContextKey, accessToken)
	ctx = context.WithValue(ctx, userIdContextKey, user.ID)
	ctx = context.WithValue(ctx, tenantIdContextKey, user.TenantID)
	return handler(ctx, request)
}

func (in *GRPCAuthInterceptor) authenticate(ctx context.Context, accessToken string) (*model.User, error) {
	if accessToken == "" {
		return nil, status.Errorf(codes.Unauthenticated, "access token not found")
	}
	claims := &ClaimsMessage{}
	_, err := jwt.ParseWithClaims(accessToken, claims, func(t *jwt.Token) (any, error) {
		if t.Method.Alg() != jwt.SigningMethodHS256.Name {
			return nil, status.Errorf(codes.Unauthenticated, "unexpected access token signing method=%v, expect %v", t.Header["alg"], jwt.SigningMethodHS256)
		}
		if kid, ok := t.Header["kid"].(string); ok {
			if kid == "v1" {
				return []byte(in.secret), nil
			}
		}
		return nil, status.Errorf(codes.Unauthenticated, "unexpected access token kid=%v", t.Header["kid"])
	})
	if err != nil {
		return nil, status.Errorf(codes.Unauthenticated, "Invalid or expired access token")
	}

	// We either have a valid access token or we will attempt to generate new access token.
	userID, err := utils.ConvertStringToInt32(claims.Subject)
	if err != nil {
		return nil, errors.Wrap(err, "malformed ID in the token")
	}
	user, err := in.handler.GetUser(ctx, &apb.FindUser{
		Id: userID,
	})
	if err != nil {
		return nil, errors.Wrap(err, "failed to get user")
	}
	if user == nil {
		return nil, errors.Errorf("user %q not exists", userID)
	}
	if user.RowStatus == cpb.RowStatus_ARCHIVED.String() {
		return nil, errors.Errorf("user %q is archived", userID)
	}

	accessTokens, err := in.handler.GetUserAccessTokens(ctx, user.ID)
	if err != nil {
		return nil, errors.Wrapf(err, "failed to get user access tokens")
	}
	if !validateAccessToken(accessToken, accessTokens) {
		return nil, status.Errorf(codes.Unauthenticated, "invalid access token")
	}

	return user, nil
}

func getTokenFromMetadata(md metadata.MD) (string, error) {
	// Check the HTTP request header first.
	authorizationHeaders := md.Get("Authorization")
	if len(md.Get("Authorization")) > 0 {
		authHeaderParts := strings.Fields(authorizationHeaders[0])
		if len(authHeaderParts) != 2 || strings.ToLower(authHeaderParts[0]) != "bearer" {
			return "", errors.New("authorization header format must be Bearer {token}")
		}
		return authHeaderParts[1], nil
	}
	// Check the cookie header.
	var accessToken string
	for _, t := range append(md.Get("grpcgateway-cookie"), md.Get("cookie")...) {
		header := http.Header{}
		header.Add("Cookie", t)
		request := http.Request{Header: header}
		if v, _ := request.Cookie(AccessTokenCookieName); v != nil {
			accessToken = v.Value
		}
	}
	return accessToken, nil
}

func validateAccessToken(accessTokenString string, userAccessTokens []*apb.AccessTokensUserSetting_AccessToken) bool {
	for _, userAccessToken := range userAccessTokens {
		if accessTokenString == userAccessToken.AccessToken {
			return true
		}
	}
	return false
}
